#-*- coding:utf-8 -*-
import time
import random
import os
import sys
import exceptions
from datetime import datetime
from dateutil import tz
import unittest




import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains  

import selenium.common.exceptions
from selenium.common.exceptions import WebDriverException

#开始


####################################以下为公共函数，请不要修改
def AgaDatetime():
	est = tz.gettz('America/New_York')
	today = datetime.utcnow()
	#aganow = datetime(today.year, today.month, today.day, today.hour,today.minute,today.second,tzinfo=tz.tzutc()).astimezone(est).strftime("%m:%d:%H:%M:%S")
	aganow = datetime.now(tz.tzutc()).astimezone(est).strftime("%m:%d:%H:%M:%S")
	agadatetime = aganow.split(':')	
	return agadatetime
def Agatime():
	agadatetime = AgaDatetime()
	time = str(agadatetime[2]) + ":" + str(agadatetime[3])+":" + str(agadatetime[4])
	return time
def AgaToday():
	agadatetime =AgaDatetime()
	today = str(agadatetime[0]) + "_" + str(agadatetime[1])
	return today
def readfilerandomline(filename,path):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	filelens = len(alllineinfos)
	randline = random.randint(0,filelens-1)
	return alllineinfos[randline].strip('\n')
def readfilerline(filename,path,infoline):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	return alllineinfos[infoline].strip('\n')
def writefilerline(filename,path,infoline,value):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	alllineinfos[infoline] = str(value)+'\n'
	f = open(os.path.join(path,filename),'w')
	f.writelines(alllineinfos)
	f.close()
def writelogfileline(log,path = "C:\\ENV\\"):
	if (path == ""):
		path = sys.path[0]
	today = AgaToday()
	logfilename = "logfile_"+ today +".txt"
	logfilename = os.path.join(path,logfilename)
	if(os.path.exists(logfilename) == False):
		f = open(logfilename,'w')
		f.close()
	f = open(logfilename,'a+')
	f.writelines(log+'\n')
	f.close()
def writetmpfileline(log,filename,path = "C:\\ENV\\"):
	if (path == ""):
		path = sys.path[0]
	tmpfilename = filename
	tmpfilename = os.path.join(path,tmpfilename)
	if(os.path.exists(tmpfilename) == False):
		f = open(tmpfilename,'w')
		f.close()
	f = open(tmpfilename,'w')
	f.writelines(log+'\n')
	f.close()

def openBrowsersetprefressfx(uaFilePath ="C:\\ENV\\UAFile.txt"):
	ualininfo = readfilerandomline(uaFilePath,"")
	fp = webdriver.FirefoxProfile()
	####set S5
	#fp.set_preference("network.proxy.type", 1)
	#fp.set_preference("network.proxy.socks","127.0.0.1")
	#fp.set_preference("network.proxy.socks_port",9951)   
	#####set ua
	fp.set_preference("general.useragent.override",ualininfo)
	fp.set_preference("media.peerconnection.enabled",False)
	#add firebug
	#fp.add_extension(extension='C:\\Documents and Settings\\nini\\Application Data\\Mozilla\\Firefox\\Profiles\\1y606se6.default\\extensions\\firebug@software.joehewitt.com.xpi')
	#fp.set_preference("extensions.firebug.currentVersion", "2.0.17");#设置firebug 版本
	#active firebug extensions
	#fp.set_preference("extensions.firebug.allPagesActivation", "on");

	fp.update_preferences()
	br = webdriver.Firefox(firefox_profile=fp)
	br.set_page_load_timeout(200)
	return br
def checkwebLink():
	return1=os.system('ping 8.8.8.8')
	if return1:
		return False
	else:
		return True

def checkwebLink2():
	import subprocess
		 
	fnull = open(os.devnull, 'w')
	return1 = subprocess.call('ping 8.8.8.8', shell = True, stdout = fnull, stderr = fnull)
	if return1:
		print 'ping fail'
	else:
		print 'ping ok'
	fnull.close()

def checkProcessCount(processname):
	p = os.popen('tasklist /FI "IMAGENAME eq %s"' % processname)
	return p.read().count(processname)


def timer_start():
	t = threading.Timer(5,watch_func)
	t.start()
def watch_func(processname,reopenCmd):
	print "I'm watch_func,"
	if get_process_count(processname) < 2 : #'python.exe'
		subprocess.Popen(reopenCmd)         #"c:\python.exe"
		print "reopen"
	timer_start()
	
	
def checkUrl(curUrl,offerUrl):
	if (curUrl.find(offerUrl)==-1):
		return False
	else:
		return True
def CCleaner(filePath = "C:/CCleaner/CCleaner.exe /AUTO"):
	os.popen(filePath)#/AUTO
#####################################以上为公共函数，请不要修改




###################################################################以下为调试参数，请修改！


debug = True         #调试时设置为True
lineinfo = 0       #修改成调试的资料的行编号
offerId = 88888     
pureUrl = "cashcorner"    #此为比较参数，务必修改！！！！
isCheckOfferUrl = False    # check pureUrl

isDebugUrl = True   #debug 还是test,务必修改！！！！
debugUrl = "http://tr.kqzamd.com/track/ccu.php?m=13231&c=38900"
testUrl = "http://www.cashcorner.org"

###################################################################调试参数结束
  
class AgaOffer(unittest.TestCase):# 不同offer只修改 test_Done函数内的部分。
	def setUp(self):
		try:
			self.printinfo = ""
			self.isSuccess = True
			if(debug == False):
				f = open(udfInputPath,'rU')
				alllineinfos = f.readlines()
				url = alllineinfos[0].strip('\n')

				infos = alllineinfos[1].strip('\n')
				self.userinfos = infos.split(',')
			else:
				if(isDebugUrl):
					url = debugUrl
				else:
					url = testUrl
				#读取userinfo文件中的一行
				userinfo = readfilerline("userInfosFile.txt","",int(lineinfo))
				self.userinfos = userinfo.split(',')
			urlStrs = url.split('=')
			self.urlNo= 8888
			if(len(urlStrs)>2):
				self.urlNo = urlStrs[2]
			print self.urlNo
			printinfo = "start "+ str(self.urlNo) + "-------userinfo------" + self.userinfos[0]+"---------" + Agatime()
			writelogfileline(printinfo)

			if(checkwebLink()==False):                   #判断网络是否正常连接
				raise Exception("web link not connected")
			print "start firefox"
			self.driver = openBrowsersetprefressfx()   #打开浏览器
			#self.driver = webdriver.Firefox()
			self.driver.delete_all_cookies()
			self.main_handle = self.driver.current_window_handle
			print url
			self.driver.get(url)    #打开链接
			time.sleep(2)
			#self.driver.maximize_window()
			curUrl = self.driver.current_url
			if(isCheckOfferUrl):
				if(checkUrl(curUrl, pureUrl) == False):  #判断是否是offer对应的url
					raise Exception("url is not correct offer url")
		except Exception as e:
			self.isSuccess = False
			print (str(e))
			writelogfileline(str(e))            #记录错误信息
			self.tearDown()                     #扫尾工作：清cookies ，写结果。
			raise Exception("setup error")

	def test_Done(self):
		try:
			driver = self.driver
			userinfos = self.userinfos
			main_handle = self.main_handle
			#########################################################
			idNo = userinfos[0]
			firstName = userinfos[18]
			lastName  = userinfos[19]
			address1  = userinfos[29]
			city  = userinfos[30]
			state  = userinfos[31]
			email  = userinfos[35]
			zipcode  = userinfos[2]
			homephone  = userinfos[34]
			workphone  = userinfos[39]
			ssnNum  = userinfos[10]
			birthYear  = userinfos[20]
			birthMonth  = userinfos[20]
			birthDay  = userinfos[20]
			driverLic  = ""
			driverState  = userinfos[25]
			company  = ""
			routing  = ""
			bankName  = ""
			bankAccount  = ""
			positionTitle  = userinfos[24]
			year = userinfos[3]
			make = userinfos[4]
			model = userinfos[5]
			owned = userinfos[7]
			use = userinfos[51]
			annualM = userinfos[9]
			gender = userinfos[21]
			credit_rating = userinfos[33]
			marital_status = userinfos[22]
			
			

			printinfoTemp =("uFistname: "+firstName + "\n"+"uLastname: "+lastName +"\n"+"uAddress: "+ address1 +"\n"+"uCity: "+ city +"\n"
			+"uState: "+ state +"\n"+"uEmail: "+ email +"\n"+"uZip: "+zipcode + "\n"+"uHomephone: "+ homephone +"\n"+"uWorkphone: "+ workphone +"\n"
			+"uSsn: "+ ssnNum +"\n"+"uBirthYear: "+ birthYear +"\n"+"uBirthMonth: "+ birthMonth +"\n"+"uBirthday: "+ birthDay +"\n"
			+"uDriverLic: "+ driverLic +"\n"+"uDriverState: "+ driverState +"\n"+"uCompany: "+ company +"\n"+"uRouting: "+ routing +"\n"+"uBankname: "+ bankName +"\n"+"uBankAccount: "+ bankAccount +"\n"
			+"uPositionTitle: "+ positionTitle +"\n")
			#writetmpfileline(printinfoTemp,"Current_UserInfos.txt","C:\\ENV\\")
			################################################################
			################################################################具体任务修改这里
			
			
			
			
			driver.find_element_by_id("email-address").clear()
			driver.find_element_by_id("email-address").send_keys(email)
			time.sleep(2)
			
			
			driver.find_element_by_id("press").click()
			time.sleep(10)
			
			#获得所有窗口
			allhandles=driver.window_handles
			#获得当前窗口
			nowhandle=driver.current_window_handle
			#循环判断窗口是否为当前窗口
			for handle in allhandles:
				if handle != nowhandle:
					driver.switch_to_window(handle)
					driver.find_element_by_id("q1_a2").click()
					time.sleep(2)
					driver.find_element_by_id("q2_a1").click()
					time.sleep(2)
					driver.find_element_by_id("q3_a1").click()
					time.sleep(2)
					driver.find_element_by_css_selector("input.btn").click()
					time.sleep(10)
					
					try:
						driver.find_element_by_xpath("//*[@id='step-1']/div[3]/div[1]").click()
					except:
						print('1')
					time.sleep(2)
					
					try:
						driver.find_element_by_xpath("//*[@id='step-2']/div[3]/div[2]").click()
					except:
						print("1")
					time.sleep(2)
					
					try:
						driver.find_element_by_xpath("//*[@id='step-3']/div[3]/div[2]").click()
					except:
						print("1")
					time.sleep(10)
					
					driver.find_element_by_name("email").clear()
					driver.find_element_by_name("email").send_keys(email)
					time.sleep(2)
					
					driver.find_element_by_id("submitbtn").click()
					time.sleep(10)
					
					driver.find_element_by_id("fn").clear()
					driver.find_element_by_id("fn").send_keys(firstName)
					time.sleep(2)
					
					driver.find_element_by_id("ln").clear()
					driver.find_element_by_id("ln").send_keys(lastName)
					time.sleep(2)
					
					driver.find_element_by_id("zp").clear()
					driver.find_element_by_id("zp").send_keys(zipcode)
					time.sleep(2)
					
					driver.find_element_by_id("subbtn").click()
					time.sleep(2)
					
					driver.find_element_by_id("ad").clear()
					driver.find_element_by_id("ad").send_keys(address1)
					time.sleep(2)
					
					driver.find_element_by_id("city").clear()
					driver.find_element_by_id("city").send_keys(city)
					time.sleep(2)
					
					Select(driver.find_element_by_css_selector("select[name=\"state\"]")).select_by_visible_text(state)
					time.sleep(2)
					
					
					strr = homephone
					strr_1 = strr[0:3]
					strr_2 = strr[3:6]
					strr_3 = strr[6:10]
					
					driver.find_element_by_id("CELLAREA").clear()
					driver.find_element_by_id("CELLAREA").send_keys(strr_1)
					time.sleep(2)
					
					driver.find_element_by_id("cell2").clear()
					driver.find_element_by_id("cell2").send_keys(strr_2)
					time.sleep(2)
					
					driver.find_element_by_id("cell3").clear()
					driver.find_element_by_id("cell3").send_keys(strr_3)
					time.sleep(2)
					
					driver.find_element_by_id("subbtn").click()
					time.sleep(2)
					
					
					
					
					#年月日
					date = birthDay
					y,m,d = date.split('/')
					d=d.strip('\t\r\n')
					m=m.strip('\t\r\n')
					y=y.strip('\t\r\n')
					if len(d) == 1:
						d = '0'+d
					if len(m) == 1:
						m = '0'+m
  
    
					ss = "//*[@name='dobmonth']/option[@value='$']"
					newdress = ss.replace('$',m) 
					driver.find_element_by_xpath(newdress).click()
					time.sleep(2)
    
					ss = "//*[@name='dobday']/option[@value='$']"
					newdress = ss.replace('$',d)
					driver.find_element_by_xpath(newdress).click()
					time.sleep(2)
    
					ss = "//*[@name='dobyear']/option[@value='$']"
					newdress = ss.replace('$',y)
					driver.find_element_by_xpath(newdress).click()
					time.sleep(2)

					##gender
					if gender == "male":
						self.accept_next_alert = True
					else:
						self.accept_next_alert = False
					time.sleep(2)
					
					driver.find_element_by_id("chkboxn").click()
					time.sleep(2)
					
       			  
					driver.find_element_by_id("subbtn").click()
					time.sleep(2)
			#回到原先的窗口
			driver.switch_to_window(nowhandle)
			
			
			
			
			################################################################具体任务修改这里
			################################################################
		except Exception as msg:
			self.isSuccess = False
			print (str(msg))
			writelogfileline(str(msg))
			raise Exception("Done offer error")
			

	def tearDown(self): #扫尾工作：清cookies ，写结果。
		print "aaaaa"
		time.sleep(1)
		if(self.isSuccess == True):
			self.printinfo = "SUCCESS "+ str(self.urlNo) + "---------userinfo------" + self.userinfos[0]+"----------"+ Agatime()
		else:
			self.printinfo = "FAIL "+ str(self.urlNo) + "---------userinfo------" + self.userinfos[0]+"----------"+ Agatime()
		writelogfileline(self.printinfo)
		#self.driver.delete_all_cookies()
		if(self.isSuccess == True):
			time.sleep(60*60)
		else:
			time.sleep(60*60)
		#self.driver.quit()


suite = unittest.TestSuite()
suite.addTest(AgaOffer('test_Done'))
runner=unittest.TextTestRunner()
runner.run(suite)






